package cn.dm.example.atomic;

import cn.dm.annoations.ThreadSafe;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@ThreadSafe
public class AtomicExample1 {

    // 请求总数
    // public static int clientTotal = 5000;
    public static int clientTotal = 1000000; // 数量调大,太小看不出效果,100w

    // 同时并发执行的线程数(用于限流)
    // public static int threadTotal = clientTotal; // 与clientTotal一致
    // public static int threadTotal = 200; // 限流
    public static int threadTotal = 1; // 数量为1,无并发

    public static AtomicInteger count = new AtomicInteger(0);

    public static void main(String[] args) throws Exception {
        long startTime = System.currentTimeMillis();
        ExecutorService executorService = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(threadTotal);
        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        for (int i = 0; i < clientTotal ; i++) {
            executorService.execute(() -> {
                try {
                    semaphore.acquire();
                    add();
                    semaphore.release();
                } catch (Exception e) {
                    log.error("exception", e);
                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        executorService.shutdown();
        long endTime = System.currentTimeMillis();
        log.info("count:{}, threadTotal: {}, cost time: {}ms",count.get(),threadTotal, (endTime-startTime));
        /*
         * 测试1
         * 15:46:06.087 [main] INFO cn.dm.example.atomic.AtomicExample1 - count:1000000, threadTotal: 1000000, cost time: 1594ms
         *
         * 测试2
         * 15:47:57.505 [main] INFO cn.dm.example.atomic.AtomicExample1 - count:1000000, threadTotal: 200, cost time: 1450ms
         *
         * 测试3
         * 15:48:29.230 [main] INFO cn.dm.example.atomic.AtomicExample1 - count:1000000, threadTotal: 1, cost time: 6044ms
         */
    }

    private static void add() {
        count.incrementAndGet();
        // count.getAndIncrement();
    }
}
